<?php
Class User extends CI_Controller{
	function __construct(){
		parent::__construct();
		//insert visit
		$this->load->library('common');
		$this->common->insert_visit();
		
		$arr_material = $this->config->item("material");
		$is_show_best_sale_ao = $this->config->item("show_best_sale_aodais");
		$is_show_new_ao = $this->config->item("show_new_aodais");
		$list_aodai_order = $this->session->userdata("arr_aodai") ;
		$this->load->model("md_type_product");
		$this->load->model("md_common");
		$this->load->library('comment');
		
		$data = array(
			"materials" => $arr_material,
			"show_best_sale" => $is_show_best_sale_ao,
			"show_new"       => $is_show_new_ao,
			"aodai_ordering" => $list_aodai_order,			
			"type_aodai"=>$this->md_type_product->get_all("1"),
			"comments"   =>$this->comment->get_all_comment(),
			"hit_visit"  =>$this->common->get_all_visit()
		);
		//load language begin
		if ($this->session->userdata("language")){
	    	$this->lang->load("label",$this->session->userdata("language"));
	    	$data["language"]= $this->session->userdata("language");
	    }else{
	    	$this->lang->load("label");
	    	$data["language"]= $this->config->item("language");
	    }
		$this->load->helper('language');
		//load language end 
		
		
		//load calendar 
		$data["calendar"] =$this->get_calendar();
		//load calendar end
		
		$this->load->model("md_product");
		if ($is_show_best_sale_ao == true){
			$data["best_sale"] = $this->md_product->get_best_sale();
		}
		if ($is_show_new_ao == true){
			$data["new_aodai"] = $this->md_product->get_new_aodai();
		}
		
		$this->load->vars($data);
		$is_admin = 0;
		if ($this->session->userdata('login_info')){
			$user_info = $this->session->userdata('login_info') ;
			
			if ($user_info -> role == 1){
				$is_admin = 1;
			}
			$this->load->vars(array(
				'user_info'=>$user_info,
				'sodo_info'=>$this->session->userdata('sodo_info')
			
				)
			);
		}else{
			//$this->load->vars('user_info',$this->session->userdata('login_info'));
		}
		$this->load->vars(array('is_admin'=>$is_admin));
		
		//load language
    	$this->lang->load("label");
    	$this->load->helper('language');
    	
	}
	function active(){
		 $this->load->model('md_user');
		 $this->md_user->active_user($this->input->get('user_id'));
		redirect(base_url("/product/home"));
	}
	function regist(){
		$dir  = "./assets/captcha/";
		foreach(glob($dir.'*.*') as $v){
			unlink($v);
		}
		if ($_POST)
			{
				$user = $_POST['txt_username'];
				$pass = $_POST['txt_password'];
				$email = $_POST['txt_email'];
				$this->load->library('form_validation');
			  	// field name, error message, validation rules
		  		$this->form_validation->set_rules('txt_username', 'User Name', 'trim|required|min_length[3]|callback_check_username_exists');
  				$this->form_validation->set_rules('txt_password', 'Password', 'trim|required|xss_clean');
  				$this->form_validation->set_rules('txt_email', 'Email', 'trim|required|min_length[3]|valid_email|unique[user.email_address]|callback_check_email_exists');
		 	 	$this->form_validation->set_rules('captcha', 'Security Code', 'trim|required|callback_check_captcha');
			  	if($this->form_validation->run() == FALSE)
			  	{
			  		$data = $this->get_captcha();
			  		$data['user_name']= $user;
			  		$data['email']= $email;
			  		$this->load->view('user/regist',$data);
			   		//$this->regist();
			  	}
				else
				{
				  //insert data
				  	 
					 $this->load->model('md_user');
					 $data  = array(
				 		'username' => $user,
				 		'password' => $pass,
				 		'email' =>$email,
				 		'ip_address' =>$this->input->ip_address()
				 		);
				 	$user_id= $this->md_user->insert_user($data) ;
				 	
				 	//send mail active
				 	$link_active ="<a href='". base_url("user/active")."?user_id=$user_id" ."'>active</a>";
				 	$this->sendmail($email,"Vui long click link để active tài khoản  $link_active ",'Active tai khoang site LeTrang');
				 	$this->load->view('user/regist_finish');
				}
				
			}else{
				
				$this->load->view('user/regist',$this->get_captcha());
			}
			
		
	}
	
	function login() {
		
		
		if ($_POST)
		{
			 $user = $_POST['txt_username'];
			 $pass = $_POST['txt_password'];
			 $this->load->model('md_user');
			 $is_valid = $this->md_user->check_exists($user,$pass);
			 if ($is_valid == 1){
			 	$user_info = $this->md_user->get_user($user,$pass) ;
			 	if ($user_info){
				 	//check co so do
				 	$info_sodo = $this->md_user->get_sodo_user($user_info->user_id) ;
				 	$this->session->set_userdata('login_info', $user_info);
				 	$this->session->set_userdata('sodo_info',$info_sodo);
				 	
				 	if ($user_info->role == 1){
				 		$this->session->set_userdata('is_admin',1);
				 	}
				 	if ($this->session->userdata('sodo_info')){
				 		redirect(base_url("/user/giohang"));
				 	}else{
				 		redirect(base_url("/product/home"));
				 	}
			 	}else{
			 		echo " Tài khoản không tồn tại hoăc chưa kích hoạt";
			 		$this->load->view('user/login');
			 	}
			 	
			 	
			 }else{
			 	redirect(base_url("/user/login"));
			 }
		}else{
				
				$this->load->view('user/login');
		}
	}
	function logout(){
		$this->session->unset_userdata("login_info");
		$this->session->unset_userdata("is_admin");
		$this->session->unset_userdata("arr_aodai");
		$this->session->unset_userdata("sodo_info");
		redirect(base_url("/user/login"));
	}
	function listproduct(){
		$this->load->view('admin/list');
	}
	function update_num(){
		$ma_aodai= $this->input->post('ma_aodai');
		$soluong= $this->input->post('soluong');
		
		$arr_aodai = $this->session->userdata("arr_aodai");
		$arr_aodai_temp = array(); 
		
		$tongtien = 0 ;
		for($i= 0 ; $i < count($arr_aodai); $i ++){
			$item = $arr_aodai[$i];
			if ($item['ma_aodai'] == $ma_aodai){
				$item['soluong'] = $soluong;
			}
			array_push($arr_aodai_temp,$item);
			$tongtien = $tongtien + ($item['soluong'] * $item['giatien']);
		}
		$this->session->set_userdata("arr_aodai",$arr_aodai_temp);
		$tongtien = preg_replace("/^(\d+)(\d\d\d)/i", "$1,$2", $tongtien);
		echo json_encode(array('status'=>"success","tongtien"=>$tongtien));
	}
	function giohang(){
	
		//if ($this->session->userdata('login_info')){			
			//luu thong tin san pham vao session
			$ma_aodai = $this->input->get("ma_aodai");
			$giatien = $this->input->get("giatien");
			$info_aodai=array(
				"ma_aodai" =>$ma_aodai,
				"soluong"  => 1,
				"giatien"  => $giatien
			);
			
			$arr_aodai = array();
			$arr_id_aodai = array();
			
			//lay thong tin tu session
			if ($this->session->userdata("arr_aodai")){
				$arr_aodai = $this->session->userdata("arr_aodai");
			}
			
			//check ma aodai co ton tai chua,neu chua thi push vao mang
			$flag_existed = 0;			
			foreach ($arr_aodai as $item){
				if ($item['ma_aodai'] == $ma_aodai){
					$flag_existed = 1;
				}
				array_push($arr_id_aodai,$item['ma_aodai']);
			}
			
			if ($flag_existed == 0){
				array_push($arr_aodai,$info_aodai);
				array_push($arr_id_aodai,$ma_aodai);
			}
			//set lai thong tin session
			$this->session->set_userdata("arr_aodai",$arr_aodai);
			
			//lay thong tin ao dai tu list cac ao dai tu session
			$this->load->model("md_common");
			$info= $this->md_common->select_where_in('aodai', 'id',$arr_id_aodai);
			
			//add them thogn tin so luong 
			for ($i = 0 ;$i < count($info) ;$i++){
				$item = $info[$i];
				$item->soluong = $arr_aodai[$i]['soluong'];
			}
			
			$data['info'] = $info;
			
			// tra ve template
			$this->load->view("user/giohang",$data);
			
//		}else{
//			echo "Vui lòng đăng kí thông tin";
//			redirect(base_url("/user/login"));
//		}
	}
	function order(){
		if ($this->session->userdata('login_info')){
			if ($_POST){
				
				$list_aodai_info = $this->session->userdata("arr_aodai") ;
				$login_info = $this->session->userdata("login_info") ;
				if ($list_aodai_info && $login_info){
					
					//lay thong tin so do
					$sodo1= $_POST['txt_sodo1'];
					$sodo2= $_POST['txt_sodo2'];
					$default_sodo = isset($_POST['ckb_default_sodo']) ? $_POST['ckb_default_sodo'] : 0 ;
		
					//lay thong tin user va ao
					$user_id = $login_info->user_id;
					
					//set thong tin don hang
					$info_donhang= array(
						'sodo1'=>$sodo1,
						'sodo2'=>$sodo2,
						'user_id'=>$user_id
					);
					
					//tao thong tin don hang
					$this->load->model('md_donhang');
					$madh= $this->md_donhang->insert_donhang($info_donhang);	

					//save sesion
					$this->session->set_userdata('madh',$madh);
					
					$aodai_info = array();
					$tongtien = 0;
					//lay thong tin list aodai
					foreach($list_aodai_info as $item){
						$tongtien = $tongtien  +  $item['soluong'] * $item['giatien'];
						array_push($aodai_info,array(
								'madh'     => $madh,
								'ma_aodai' => $item['ma_aodai'],
								'giatien'  => $item['giatien'],
								'soluong'  => $item['soluong']
							) 
						);
					}
					//save sesion
					$this->session->set_userdata('tongtien',$tongtien);
					
					//update tong tien cua don hang
					$this->load->model("md_common");
					$this->md_common->update('donhang',array('tongtien'=>$tongtien),array('madh'=>$madh));
					
					$this->load->model("md_user");
					//tao thong tin don hang chi tiet
					$this->md_donhang->insert_donhang_chitiet($aodai_info);
					// tao thong tin so do defaul
					if ($default_sodo == 1){
						
						$this->md_user->insert_sodo_user($info_donhang);
					}
					
					$info_sodo = $this->md_user->get_sodo_user($user_id) ;
				 	$this->session->set_userdata('sodo_info',$info_sodo);
				 	
				 	//xoa don hang 
				 	$this->session->unset_userdata("arr_aodai");
				 	
					//gui mail thong bao dat hang thanh cong
					// send an email  
					//$this->sendmail($login_info->email,"Đã đặt hàng thành công ,mã đơn hàng của bạn là : $madh ",'Ao dai Le Trang');
					redirect(base_url("/user/order_pay"));
					
					}
				}else{
					
					$this->load->view("user/order/order");
				}
		}
		else{
				echo "Vui lòng đăng kí thông tin";
				redirect(base_url("/user/login"));
			}
		
	}
	function order_pay(){
		$ma_dh = $this->session->userdata('madh');
		$total_price = $this->session->userdata('tongtien');
		
		$this->load->library('paypal_lib');
		$this->paypal_lib->add_field('business', 'colu85@yahoo.com');
	    $this->paypal_lib->add_field('return', base_url('user/order_finish'));
	    $this->paypal_lib->add_field('cancel_return', base_url('paypal/cancel'));
	    $this->paypal_lib->add_field('notify_url', base_url('paypal/ipn')); // <-- IPN url
	    $this->paypal_lib->add_field('custom', '1234567890'); // <-- Verify return
	    $this->paypal_lib->add_field('noshipping', '1');

	    $this->paypal_lib->add_field('item_name', 'Paypal Transaction');
	    $this->paypal_lib->add_field('item_number', $ma_dh);
	    $this->paypal_lib->add_field('amount', $total_price);

		// if you want an image button use this:
		$this->paypal_lib->image('btn_paynowCC_LG.gif');
		
		// otherwise, don't write anything or (if you want to 
		// change the default button text), write this:
		// $this->paypal_lib->button('Click to Pay!');
	    $data['paypal_form'] = $this->paypal_lib->paypal_form();
		$this->load->view('user/order/order_pay', $data);
	}
	function order_finish(){
		$this->load->view('user/order/order_finish');
	}
	function update_order_pay_type(){
		$type = $this->input->post("type");
		$madh = $this->session->userdata('madh');
		
		$this->load->model('md_common');
		$this->md_common->update("donhang",array('pay_type'=>$type) , array('madh'=>$madh));	
	}
	function sendmail($email,$content,$title){

		// send an email  

		$this->load->library('email');
		 

		$this->email->from('colu85@gmail.com','Ao dai Le Trang');  

		$this->email->to($email);  

		$this->email->subject($title);  

		$this->email->message("<b>$content</b>");  

		if ($this->email->send()){
			echo "da send mail";
			echo $this->email->print_debugger();
		}else{
			echo $this->email->print_debugger();
		}
			

	}
	function sodo(){
		$login_info = $this->session->userdata("login_info") ;
		$type = $this->input->get("type");
		$this->load->model("md_user");
		if ($_POST){
			
			//lay thong tin so do
			$sodo1= $_POST['txt_sodo1'];
			$sodo2= $_POST['txt_sodo2'];
			//set thong tin so do
			$info_sodo= array(
				'sodo1'=>$sodo1,
				'sodo2'=>$sodo2,
				'user_id'=>$login_info->user_id
			);
			$this->md_user->update_sodo_user($info_sodo);
			$data['sodo']= $this->md_user->get_sodo_user($login_info->user_id);
			$data['type']= 'view';
			$this->load->view("user/sodo",$data);
		}else{
			$data['sodo']= $this->md_user->get_sodo_user($login_info->user_id);
			$data['type']= $type;
			
			$this->load->view("user/sodo",$data);
		}
		
	}
	function edit_sodo(){
		$this->load->view("user/sodo");
	}
	function get_calendar(){
		$this->lang->load('calendar', $this->session->userdata("language"));
		$template = '

		   {table_open}<table  cellpadding="0" cellspacing="0" class="calendar" >{/table_open}
		
		   {heading_row_start}<tr>{/heading_row_start}
		
		   {heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
		   {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
		   {heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}
		
		   {heading_row_end}</tr>{/heading_row_end}
		
		   {week_row_start}<tr>{/week_row_start}
		   {week_day_cell}<td>{week_day}</td>{/week_day_cell}
		   {week_row_end}</tr>{/week_row_end}
		
		   {cal_row_start}<tr>{/cal_row_start}
		   {cal_cell_start}<td>{/cal_cell_start}
		
		   {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
		   {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}
		
		   {cal_cell_no_content}{day}{/cal_cell_no_content}
		   {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
		
		   {cal_cell_blank}&nbsp;{/cal_cell_blank}
		
		   {cal_cell_end}</td>{/cal_cell_end}
		   {cal_row_end}</tr>{/cal_row_end}
		
		   {table_close}</table>{/table_close}
		';
			  
		$prefs = array (
			 'start_day'    => 'monday',
               //'show_next_prev'  => TRUE,
               //'next_prev_url'   => 'http://example.com/index.php/calendar/show/',
               
               'template'        => $template
             );

		$this->load->library('calendar', $prefs);

	
		return $this->calendar->generate();
	}
	function get_captcha(){
		$this->load->helper('captcha');
		  $vals = array(
		     'img_path' => '../assets/captcha/',
		     'img_url' => base_url('assets/captcha/')
		     );
		  $cap = create_captcha($vals);
		  $data = array(
		     'captcha_time' => $cap['time'],
		     'ip_address' => $this->input->ip_address(),
		     'word' => $cap['word']
		     );
		  $this->session->set_userdata($data);
		  $data['cap_img']=$cap['image'];
		return $data;
	}
	function validate_regist(){
		
		$this->load->library('form_validation');
	  	// field name, error message, validation rules
	  	$this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[3]');
	  	$this->form_validation->set_rules('message', 'Message', 'trim|required|xss_clean');
	 	 $this->form_validation->set_rules('captcha', 'Security Code', 'trim|required|callback_check_captcha');
	  	if($this->form_validation->run() == FALSE)
	  	{
	   		$this->regist();
	  	}
		else
		{
		  $this->home_model->add_message();
		}
		
		
	}
	function check_captcha(){
		//check captcha
		$expiration = time()-7200; // Two hour limit
  		$cap=$this->input->post('captcha');
	  	if($this->session->userdata('word')== $cap 
	   	AND $this->session->userdata('ip_address')== $this->input->ip_address()
	   	AND $this->session->userdata('captcha_time')> $expiration)
	  	{
	   		return true;
	  	}
	  	else{
	   		$this->form_validation->set_message('check_captcha', 'Security number does not match.');
	   		return false;
	  	}
	  	//check captcha END
	}
	function check_email_exists($email){
		 $this->load->model('md_user');
		 $is_exist = $this->md_user->check_email_exists($email);
		 if ($is_exist == 0){
		 	return true;
		 }else{
		 	$this->form_validation->set_message('check_email_exists', 'Email is registed');
	   		return false;
		 }
	}
	function check_username_exists($user,$pass){
	 	 $this->load->model('md_user');
		 $is_exist = $this->md_user->check_exists($user,"");
		 if ($is_exist == 0){
		 	return true;
		 }else{
		 	$this->form_validation->set_message('check_username_exists', 'Username is registed');
	   		return false;
		 }
	}
	function contact(){
		$this->load->view("contact");
	}
	function test(){
		$this->load->library('common');
		$this->common->hello();
		//echo shell_exec();
		//$this->sendmail("colu85@yahoo.com","hello mot","send mail test");
		//$this->load->view('test');
		//echo phpinfo();
	}
	/****************************************Xu Ly COMMENT ***************************************/
	
	/****************************************Xu Ly COMMENT  END***************************************/
}

?>


